package com.chookss.video;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.chookss.R;
import com.chookss.tools.MyEvent;
import com.chookss.tools.Utils;
import com.chookss.video.recommend.RecommendedFragment;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.ImmersionFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class VideoMainFragments extends ImmersionFragment {

    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.ivLeft)
    ImageView ivLeft;
    @BindView(R.id.ivDirectory)
    ImageView ivDirectory;
    @BindView(R.id.rlDirectory)
    RelativeLayout rlDirectory;
    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.rbFans)
    RadioButton rbFans;
    @BindView(R.id.rbRank)
    RadioButton rbRank;
    @BindView(R.id.rbRrecommed)
    RadioButton rbRrecommed;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.insetsLayout)
    RelativeLayout insetsLayout;
    private Activity mContext;
    Unbinder unbinder;
    private MyAdapter pagerAdapter;
    private VideoFragment fansFragment;
    private VideoSmallFragment smallFragment;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private int index = 2;
    private int type = 0; //0一级页面没有返回1是activity要返回
    public OnFragmentInteractionListener mListener;

    public VideoMainFragments() {

    }

    public VideoMainFragments(int type,int index) {
        this.type = type;
        this.index = index;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(int index);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
        mListener = (OnFragmentInteractionListener) mContext;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_video_main, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        init();
        return view;
    }

    class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(@NonNull FragmentManager fm, List<Fragment> fragments) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    private void init() {
        int statusBarHeight = Utils.getStatusBarHeight(mContext);
        RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) statusBar.getLayoutParams();
        topAllParams.height = statusBarHeight;
        statusBar.setLayoutParams(topAllParams);
        //顶部状态栏 处理
        if (type == 0) {
            ivBack.setVisibility(View.GONE);
            ivLeft.setVisibility(View.VISIBLE);
        } else {
            rlDirectory.setVisibility(View.VISIBLE);
            ivBack.setVisibility(View.VISIBLE);
            ivLeft.setVisibility(View.GONE);
        }
        fansFragment = new VideoFragment();
        smallFragment = new VideoSmallFragment();
        fragments.add(fansFragment);
        fragments.add(smallFragment);
        fragments.add(new RecommendedFragment());
        pagerAdapter = new MyAdapter(getChildFragmentManager(), fragments);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(2);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                index = position;
                updateButtons(position);
                if (mListener != null) {
                    mListener.onFragmentInteraction(position);
                }
                initImmersionBar();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int check = 0;
                if (checkedId == rbFans.getId()) {
                    check = 0;
                } else if (checkedId == rbRank.getId()) {
                    check = 1;
                } else if (checkedId == rbRrecommed.getId()) {
                    check = 2;
                }
                viewPager.setCurrentItem(check);
                if (check == 0) {
                    fansFragment.loadPlayList(false);
                }
            }
        });
        viewPager.setCurrentItem(index);
    }

    private boolean isOpenLight = false;

    private void updateButtons(int selectIndex) {
        if (selectIndex == 2) {
            isOpenLight = false;
            Utils.keepScreenLongLight(getActivity(), isOpenLight);
        } else {
            if (!isOpenLight) {
                isOpenLight = true;
                Utils.keepScreenLongLight(getActivity(), isOpenLight);
            }
        }
        for (int i = 0; i < 3; i++) {
            RadioButton radioButton = (RadioButton) radioGroup.getChildAt(i);
            if (selectIndex == 0 || selectIndex == 1) {
                if (selectIndex == i) {
                    radioButton.setTextColor(getResources().getColor(R.color.white));
                } else {
                    radioButton.setTextColor(getResources().getColor(R.color.white_9f));
                }
                if (type == 1) {
                    ivBack.setBackgroundResource(R.drawable.icon_back);
                    ivDirectory.setBackgroundResource(R.drawable.icon_menu);
                } else {
                    ivLeft.setBackgroundResource(R.drawable.icon_menu);
                }
                ivRight.setBackgroundResource(R.drawable.search_white_icon);
            } else {
                if (selectIndex == i) {
                    radioButton.setTextColor(getResources().getColor(R.color.main_color));
                } else {
                    radioButton.setTextColor(getResources().getColor(R.color.text_gray3));
                }
                if (type == 1) {
                    ivBack.setBackgroundResource(R.drawable.icon_back_black);
                    ivDirectory.setBackgroundResource(R.drawable.icon_menu_black);
                } else {
                    ivLeft.setBackgroundResource(R.drawable.icon_menu_black);
                }
                ivRight.setBackgroundResource(R.drawable.search_black);
            }
        }
    }

    @Override
    public void initImmersionBar() {
        if (getActivity() == null) {
            return;
        }
        if (index == 2) {
            insetsLayout.setBackgroundColor(Color.parseColor("#ffffff"));
            ImmersionBar.with(getActivity())
                    .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                    .statusBarDarkFont(true)
                    .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                    .keyboardEnable(false).navigationBarEnable(false)
                    .init();
        } else {
            insetsLayout.setBackgroundColor(Color.parseColor("#000000"));
            ImmersionBar.with(getActivity())
                    .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                    .statusBarDarkFont(false)
                    .flymeOSStatusBarFontColor(R.color.white)  /*修改flyme OS状态栏字体颜色*/
                    .keyboardEnable(false).navigationBarEnable(false)
                    .init();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("HomeVedio1")) {
                radioGroup.check(rbRank.getId());
                index = 1;
                updateButtons(1);
                if (mListener != null) {
                    mListener.onFragmentInteraction(1);
                }
                initImmersionBar();
            } else if (msg.equals("HomeVedio2")) {
                radioGroup.check(rbRrecommed.getId());
                index = 2;
                updateButtons(2);
                if (mListener != null) {
                    mListener.onFragmentInteraction(2);
                }
                initImmersionBar();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
        mListener = null;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();

        fansFragment.setStoped(!(isResumed() && !isHidden() && getUserVisibleHint()));
        smallFragment.setStoped(!(isResumed() && !isHidden() && getUserVisibleHint()));

    }

    @Override
    public void onPause() {
        super.onPause();
        fansFragment.setStoped(!(isResumed() && !isHidden() && getUserVisibleHint()));
        smallFragment.setStoped(!(isResumed() && !isHidden() && getUserVisibleHint()));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        fansFragment.setStoped(!(isResumed() && !isHidden() && getUserVisibleHint()));
        smallFragment.setStoped(!(isResumed() && !isHidden() && getUserVisibleHint()));
    }

    @OnClick({R.id.rlLeft,R.id.rlDirectory, R.id.rlRight})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlLeft:
                if (type == 0) {
//                    Intent intent = new Intent(mContext, VideoCatesActivity.class);
                    Intent intent = new Intent(mContext, VideoNewCatesActivity.class);
                    if (index == 2) {
                        intent.putExtra("videoType", "2");
                    } else {
                        intent.putExtra("videoType", "1");
                    }
                    mContext.startActivity(intent);
                } else {
                    if (mContext != null) {
                        mContext.finish();
                    }
                }
                break;
            case R.id.rlDirectory:
//                Intent intent = new Intent(mContext, VideoCatesActivity.class);
                Intent intent = new Intent(mContext, VideoNewCatesActivity.class);
                if (index == 2) {
                    intent.putExtra("videoType", "2");
                } else {
                    intent.putExtra("videoType", "1");
                }
                mContext.startActivity(intent);
                break;
            case R.id.rlRight:
                mContext.startActivity(new Intent(mContext, VideoSearchActivity.class));
                break;
        }
    }
}
